'敌人管理器，用于敌人的生成和管理'

extends Node

const SPAWN_RADIUS = 375#敌人生成的半径

@export var basic_enemy_scene : PackedScene
@export var wizard_enemy_scene : PackedScene
@export var bat_enemy_scene: PackedScene
@export var arena_time_manager: Node
@onready var timer = $Timer

var time_record = 0#时间计数器，结束时生成敌人
var enemy_table = WeightedTable.new()

func _ready() -> void:
	enemy_table.add_item(basic_enemy_scene,100)
	enemy_table.add_item(wizard_enemy_scene,0)
	enemy_table.add_item(bat_enemy_scene,0)
	time_record = timer.wait_time
	timer.timeout.connect(on_timer_timeout)
	arena_time_manager.arena_difficulty_increased.connect(on_arena_difficulty_increased)
	pass

#在玩家的周围（屏幕外）生成敌人
func get_spawn_positio(player:CharacterBody2D) -> Vector2:
	var spawn_position = Vector2.ZERO
	var random_direction = Vector2.RIGHT.rotated(randf_range(0,TAU))
	for i in 4:		
		spawn_position = player.global_position + random_direction * SPAWN_RADIUS
		var add_check_offset = random_direction * 20
		var query_paramaters = PhysicsRayQueryParameters2D.create(player.global_position,\
		spawn_position + add_check_offset,1)
		var result = self.get_tree().root.world_2d.direct_space_state.intersect_ray(query_paramaters)
		
		if result.is_empty():
			return spawn_position
		else:
			random_direction = random_direction.rotated(deg_to_rad(90))
	return Vector2(8,8)

#时间结束时生成敌人
func on_timer_timeout() -> void:
	timer.start()
	var player = get_tree().get_first_node_in_group("player")
	if player == null:
		return
	
	#var enemy = chosen_enemy()
	var enemy = enemy_table.pick_item()[0].instantiate()
	enemy.global_position = get_spawn_positio(player)
	self.get_tree().get_first_node_in_group("entities_layer").add_child(enemy)
	pass

#升级难度。增加敌人的种类和减少生成时间
func on_arena_difficulty_increased(arena_difficult: int) -> void:
	#difficult = arena_difficult
	var time_off = (.1 / 12) * arena_difficult
	time_off = min(time_off, 0.7)
	timer.wait_time = time_record - time_off
	enemy_table.change_weight(basic_enemy_scene,-1)
	enemy_table.change_weight(wizard_enemy_scene,1)
	if arena_difficult == 18:
		enemy_table.change_weight(basic_enemy_scene,-10)
		enemy_table.change_weight(bat_enemy_scene,10)
	pass
